package com.mingqi.enetconnected.view.decoration;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.mingqi.enetconnected.R;

/**
 * @author yaxi
 * @date 2018/9/17
 */
public class DottedLineDecoration extends RecyclerView.ItemDecoration {

    private int marginLeft = 0;
    private int marginRight = 0;
    /**
     * 分割线高度
     */
    private int dividerHeight = 4;
    /**
     * 虚线的每个单元宽度
     */
    private int dottedLineCellWidth = 20;

    private Paint paint;

    public DottedLineDecoration(Context context) {
        paint = new Paint();
        paint.setStrokeWidth(dividerHeight);
        paint.setColor(context.getResources().getColor(R.color.space));
    }

    public DottedLineDecoration(Context context, int marginLeft, int marginRight) {
        this(context);
        this.marginLeft = marginLeft;
        this.marginRight = marginRight;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount - 1; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            int left = child.getLeft() + marginLeft;
            int right = child.getRight() - marginRight;
//            int bottom = child.getBottom() + dividerHeight;
            int bottom = child.getBottom();
            int count = (right - left) / dottedLineCellWidth / 2 + 1;
            for (int j = 0; j < count; j++) {
                int start = left + j * dottedLineCellWidth * 2;
                int end = start + dottedLineCellWidth;
                float[] pts = new float[]{start, bottom, end, bottom};
                c.drawLines(pts, paint);
            }


        }


    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(0, 0, 0, dividerHeight);
    }


    public void setMarginLeft(int marginLeft) {
        this.marginLeft = marginLeft;
    }

    public void setMarginRight(int marginRight) {
        this.marginRight = marginRight;
    }

    public void setDividerHeight(int dividerHeight) {
        this.dividerHeight = dividerHeight;
    }

    public void setDottedLineCellWidth(int dottedLineCellWidth) {
        this.dottedLineCellWidth = dottedLineCellWidth;
    }
}
